import { useRef, MouseEvent, RefObject, forwardRef, useImperativeHandle, Ref } from 'react'
import style from './tab.module.less'

interface Props {
  title: string
  active: boolean
  onClick: () => void
  closeHandle?: () => void
}

export interface TabSchema {
  tabRef: RefObject<HTMLDivElement>
}

function Main ({ title, active, onClick, closeHandle }: Props, ref: Ref<TabSchema>) {
  const tabRef = useRef<HTMLDivElement>(null)
  const s = [style.tab]
  if (active) {
    s.push(style.active)
  }
  useImperativeHandle(ref, () => {
    return {
      tabRef
    }
  })
  return (
    <div ref={tabRef} className={s.join(' ')} onClick={() => onClick()}>
      <span className={style['tab-text']}>{title}</span>
      {
        typeof closeHandle === 'function' && (
          <span className={style['tab-close']} onClick={e => { e.stopPropagation(); closeHandle() }}>x</span>
        )
      }
    </div>
  )
}

export default forwardRef(Main)
